<template>
  <el-select
    v-model="l_productionid"
    filterable
    ref="prod"
    remote
    reserve-keyword
    placeholder="请输入关键词"
    :remote-method="productionSearch"
    :loading="loading"
    :disabled="disabled"
    @change="selectChanged"
    @visible-change="visiableChange"
  >
    <el-option
      v-for="item in productions"
      :key="item.AutoId"
      :label="item.Name"
      :value="item.AutoId"
    >
      <span style="float: left">{{ item.Name }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.Code }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { ListByKeyword } from '@/api/production'

export default {
  data() {
    return {
      loading: false,
      productions: [],
      l_productionid: null
    }
  },
  model: {
    prop: 'productionId',
    event: 'productionSelected'
  },
  props: ['productionId', 'disabled'],
  mounted() {
    let keyword = this.productionId ? this.productionId : '%'
    this.search(keyword)
    this.l_productionid = this.productionId
  },
  watch: {
    productionId: function(value) {
      this.l_productionid = value
    }
  },
  methods: {
    search(keywords) {
      ListByKeyword(keywords)
        .then(response => {
          this.productions = response.Data
        })
        .catch(error => {
          console.log(error)
          this.productions = []
        })
    },
    productionSearch(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.search(query)
        }, 400)
      } else {
        this.productions = []
      }
    },
    selectChanged(params) {
      for (let i = 0; i < this.productions.length; i++) {
        if (this.productions[i].AutoId === params) {
          this.$emit('productionSelected', this.productions[i])
          return
        }
      }
    },
    visiableChange(params) {
      this.$emit('selectorVisiableChange', params)
    },
    focus() {
      this.$refs.prod.focus()
    }
  }
}
</script>